package net.lahuobao.finance.controller.payrate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.lahuobao.finance.entity.accredit.AccreditApplyInfo;
import net.lahuobao.finance.service.accredit.IAccreditService;
import org.apache.log4j.Logger;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.logicalcobwebs.proxool.admin.Admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.core.util.MyBeanUtils;

import net.lahuobao.finance.dao.CargoOwnerPayRatesDetailMapper;
import net.lahuobao.finance.dao.CargoOwnerPayRatesMapper;
import net.lahuobao.finance.dao.StewardMapper;
import net.lahuobao.finance.entity.payrate.CargoOwnerPayRatesEntity;
import net.lahuobao.finance.entity.payratedetail.CargoOwnerPayRatesDetailEntity;
import net.lahuobao.finance.entity.steward.EStewardState;
import net.lahuobao.finance.entity.steward.Steward;
import net.lahuobao.finance.service.payrate.CargoOwnerPayRatesServiceI;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.jeecgframework.core.beanvalidator.BeanValidators;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.net.URI;
import org.springframework.http.MediaType;
import org.springframework.web.util.UriComponentsBuilder;

/**   
 * @Title: Controller
 * @Description: 货主费率设置
 * @author zhangdaihao
 * @date 2016-08-24 15:51:02
 * @version V1.0   
 *
 */
@Controller
@RequestMapping("/cargoOwnerPayRatesController")
public class CargoOwnerPayRatesController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(CargoOwnerPayRatesController.class);

	@Autowired
	private CargoOwnerPayRatesServiceI cargoOwnerPayRatesService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private Validator validator;
	@Autowired
	private CargoOwnerPayRatesMapper cargoOwnerPayRatesDao;
	@Autowired
	private CargoOwnerPayRatesDetailMapper cargoOwnerPayRatesDetailDao;
	@Autowired
	private StewardMapper stewardDao;
	@Autowired
	private IAccreditService accreditService;

	/**
	 * 货主费率设置列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "list")
	public ModelAndView list(HttpServletRequest request) {
		  String statesReplace = "";
	      List<Map> stateList = cargoOwnerPayRatesDao.selectStewardStates();
	      for (Map map : stateList) {
	            if (statesReplace.length() > 0) {
	            	statesReplace += ",";
	            }
	            statesReplace += map.get("codevalue")+ "_" + map.get("code");
	       }
	       request.setAttribute("statesReplace", statesReplace);
		return new ModelAndView("net/lahuobao/finance/payrate/cargoOwnerPayRatesList");
	}

	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(CargoOwnerPayRatesEntity cargoOwnerPayRates,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        String stewardStatus = request.getParameter("steward.state");
        String organizationName = request.getParameter("organization.name");
        Map map  = new HashMap();
        if(null==stewardStatus || stewardStatus.equals("")){
            map.put("stewardStatus", 0);
        }else{
            map.put("stewardStatus", Integer.parseInt(stewardStatus));
        }
        map.put("organizationName", organizationName);
        List<Map>  stewardList= cargoOwnerPayRatesDao.selectStewardListFilter(map);
        dataGrid.setResults(stewardList);
		TagUtil.datagrid(response, dataGrid);
	}

	
	/**
	 * 货主费率设置
	 * 
	 * @return
	 */
	@RequestMapping(params = "view")
	public ModelAndView view(CargoOwnerPayRatesEntity cargoOwnerPayRates, HttpServletRequest request) {
		ModelAndView mv = new ModelAndView("net/lahuobao/finance/payratedetail/cargoOwnerPayRatesDetail");
		Map model = mv.getModel();
		//服务商
		List<Map> carriers = cargoOwnerPayRatesDao.getCarrier();
		//承运商
		List<Map> services =cargoOwnerPayRatesDao.getService();
		//数据主体
		List<Map> dataOwners = cargoOwnerPayRatesDao.getDataowner();
		//垫付机构
		List<Map> advances = cargoOwnerPayRatesDao.getAdvance();
	    
		Integer organizationId = Integer.parseInt(request.getParameter("id"));
		String review = request.getParameter("review");
		if(review != null && review.equals("true")){
			AccreditApplyInfo accreditApplyInfo = accreditService.getByOrganizationId(organizationId);
			request.setAttribute("review",accreditApplyInfo != null ? true : false);
			request.setAttribute("accreditApplyInfo",accreditApplyInfo);
		}else {
			request.setAttribute("review",false);
		}
		Steward steward=stewardDao.selectByPrimaryKey(organizationId);
		model.put("steward", steward);
		CargoOwnerPayRatesDetailEntity cargoOwnerPayRateDetail=cargoOwnerPayRatesDetailDao.selectByorganizationId(organizationId);
		model.put("cargoOwnerPayRateDetail", cargoOwnerPayRateDetail);
		Map organMap = cargoOwnerPayRatesDao.selectPayRateByorganizationId(organizationId);
		if(null!=organMap){
		    request.setAttribute("serviceProviderId", organMap.get("serviceProviderId"));
		    request.setAttribute("carrierId", organMap.get("carrierId"));
		    request.setAttribute("dataSourceId", organMap.get("dataSourceId"));
		    request.setAttribute("advancedId", organMap.get("advancedId"));
		    request.setAttribute("payRateId", organMap.get("id"));

		}
		
		Map map  = new HashMap();
	    map.put("organizationId", organizationId);
		List<Map> relist=cargoOwnerPayRatesDao.selectStewardListFilter(map);//唯一一条
		if(!CollectionUtils.isEmpty(relist)){
			//organization_name 有null的情况
			String organizationName="";
			if(null!= relist.get(0).get("organization_name")){
				organizationName=relist.get(0).get("organization_name").toString();
			}
			 request.setAttribute("organizationName", organizationName);
		}
		 
	    request.setAttribute("carriers", carriers);
	    request.setAttribute("services", services);
	    request.setAttribute("dataOwners", dataOwners);
	    request.setAttribute("advances", advances);


		return mv;
	}
	/**
	 * 
	 * @param steward 物流管家信息
	 * @param detail 费率明细
	 * @param payRate 组织机构
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(params = "firstPass")
    public String firstPass(Steward steward,CargoOwnerPayRatesDetailEntity detail,CargoOwnerPayRatesEntity payRate,HttpServletRequest request) throws Exception {
		updateManagerLogistics(steward,detail,payRate, EStewardState.WAIT_FINANCIAL_VALIDATE.getValue(), true,request);
        return "redirect:cargoOwnerPayRatesController.do?list";
	}
	/**
	 * 驳回
	 * @param steward
	 * @param detail
	 * @param payRate
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(params = "reject", method = {RequestMethod.POST})
	public String reject(Steward steward,CargoOwnerPayRatesDetailEntity detail,CargoOwnerPayRatesEntity payRate,HttpServletRequest request) throws Exception {
	        updateManagerLogistics(steward,detail,payRate, EStewardState.DENY.getValue(), false,request);
	        return "redirect:cargoOwnerPayRatesController.do?list";

	 }
	/**
	 * 财务审核通过
	 * @param steward
	 * @param detail
	 * @param payRate
	 * @param request
	 * @return
	 * @throws Exception
	 */
	 @RequestMapping(params = "detailPass")
	    public String adjustPass(Steward steward,CargoOwnerPayRatesDetailEntity detail,CargoOwnerPayRatesEntity payRate,HttpServletRequest request) throws Exception {
	        updateManagerLogistics(steward,detail,payRate, EStewardState.VALIDATED.getValue(), true,request);
	        return "redirect:cargoOwnerPayRatesController.do?list";
	    }
	 /**
		 * 已开通-修改
		 * @param steward
		 * @param detail
		 * @param payRate
		 * @param request
		 * @return
		 * @throws Exception
		 */
		 @RequestMapping(params = "modify")
		    public String modify(Steward steward,CargoOwnerPayRatesDetailEntity detail,CargoOwnerPayRatesEntity payRate,HttpServletRequest request) throws Exception {
		        updateManagerLogistics(steward,detail,payRate, EStewardState.VALIDATED.getValue(), true,request);
		        return "redirect:cargoOwnerPayRatesController.do?list";
		 }
		 @RequestMapping(params = "frozen")
		    public String frozen(Steward steward,CargoOwnerPayRatesDetailEntity detail,CargoOwnerPayRatesEntity payRate,HttpServletRequest request) throws Exception {
		        updateManagerLogistics(steward,detail,payRate, EStewardState.FREEZE.getValue(), false,request);
		        return "redirect:cargoOwnerPayRatesController.do?list";
		    }
	/**
	 * 
	 * @param steward 物流管家信息
	 * @param detail 费率明细
	 * @param payRate 组织机构
	 * @param state 物流管家开通状态
	 * @param isUpdate 是否更新
	 */
	private void updateManagerLogistics(Steward steward,CargoOwnerPayRatesDetailEntity detail,CargoOwnerPayRatesEntity payRate, short state, boolean isUpdate,HttpServletRequest request){
        Steward orgrinSteward = stewardDao.selectByPrimaryKey(steward.getOrganizationId());
        String payRateId = request.getParameter("payRateId");
        String detailId = request.getParameter("detailId");
        if(null!=payRateId && !payRateId.equals("")){
        	payRate.setId(payRateId);
        }
        if(null!=detailId && !detailId.equals("")){
        	detail.setId(Integer.parseInt(detailId));
        }
        if (isUpdate) {
        	if(steward.getAllowManagementFee()!=null){
        		orgrinSteward.setAllowManagementFee(steward.getAllowManagementFee());
        	}else{
        		orgrinSteward.setAllowManagementFee(false);
        	}
        	if(steward.getServiceFee()!=null){
        		orgrinSteward.setServiceFee(steward.getServiceFee());
        	}
        	if(steward.getCarrierFee()!=null){
        		orgrinSteward.setCarrierFee(steward.getCarrierFee());
        	}
            if (steward.getManagementFee() != null)
                orgrinSteward.setManagementFee(steward.getManagementFee());
            
            if (steward.getAllowPayment() != null)
                orgrinSteward.setAllowPayment(steward.getAllowPayment());
            else
                orgrinSteward.setAllowPayment(false);

            if (steward.getPaymentLimit() != null)
                orgrinSteward.setPaymentLimit(steward.getPaymentLimit());
            if (steward.getAllowInvoice() != null){
            	if(steward.getAutoInvoice()!=null){
                    orgrinSteward.setAutoInvoice(steward.getAutoInvoice());
            	}else{
                    orgrinSteward.setAutoInvoice(false);

            	}
                orgrinSteward.setAllowInvoice(steward.getAllowInvoice());
            }
            else{
                orgrinSteward.setAllowInvoice(false);
                orgrinSteward.setAutoInvoice(false);
            }
            if (steward.getInvoiceTitle() != null)
                orgrinSteward.setInvoiceTitle(steward.getInvoiceTitle());
            if (steward.getInvoiceRate() != null)
                orgrinSteward.setInvoiceRate(steward.getInvoiceRate());
            if (steward.getAllowInsurance() != null)
                orgrinSteward.setAllowInsurance(steward.getAllowInsurance());
            else
                orgrinSteward.setAllowInsurance(false);

            if (steward.getAllowBaseInsurance() != null)
                orgrinSteward.setAllowBaseInsurance(steward.getAllowBaseInsurance());
            else
                orgrinSteward.setAllowBaseInsurance(false);

            if (steward.getBaseInsuranceRate() != null)
                orgrinSteward.setBaseInsuranceRate(steward.getBaseInsuranceRate());

            if (steward.getAllowMixtureInsurance() != null)
                orgrinSteward.setAllowMixtureInsurance(steward.getAllowMixtureInsurance());
            else
                orgrinSteward.setAllowMixtureInsurance(false);

            if (steward.getMixtureInsuranceRate() != null)
                orgrinSteward.setMixtureInsuranceRate(steward.getMixtureInsuranceRate());
            if (null!=steward.getAllowDaily()) {
                orgrinSteward.setAllowDaily(true);
                orgrinSteward.setAllowMonthly(false);
                orgrinSteward.setDailyRate(steward.getDailyRate());
            }
            else{
                orgrinSteward.setAllowDaily(false);
                orgrinSteward.setAllowMonthly(true);
                orgrinSteward.setMonthlyRate(steward.getMonthlyRate());
            }

            if (steward.getAllowUnify() != null) {
                orgrinSteward.setAllowUnify(steward.getAllowUnify());
            }

            if (steward.getContractNumber() != null)
                orgrinSteward.setContractNumber(steward.getContractNumber());
            if (steward.getSalesman() != null) {
                orgrinSteward.setSalesman(steward.getSalesman());
            }
            Boolean hasOtherFee = steward.getHasOtherFee();
            if (null==hasOtherFee) {
                orgrinSteward.setHasOtherFee(false);
            }else {
                orgrinSteward.setHasOtherFee(hasOtherFee);
            }
            Boolean allowFee = steward.getAllowFee();
            if (null==allowFee) {
                orgrinSteward.setAllowFee(false);
            }else {
                orgrinSteward.setAllowFee(allowFee);
            }
            orgrinSteward.setCanShunt(steward.getCanShunt());
            orgrinSteward.setToTransport(steward.getToTransport());
        }else{
        	detail=null;  
        	payRate=null;
        }
        orgrinSteward.setStewardState(state);
		cargoOwnerPayRatesService.updateSteward(orgrinSteward, detail, payRate);
	}
	/**
	 * 删除货主费率设置
	 * 
	 * @return
	 */
	@RequestMapping(params = "del")
	@ResponseBody
	public AjaxJson del(CargoOwnerPayRatesEntity cargoOwnerPayRates, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		cargoOwnerPayRates = systemService.getEntity(CargoOwnerPayRatesEntity.class, cargoOwnerPayRates.getId());
		message = "货主费率设置删除成功";
		cargoOwnerPayRatesService.delete(cargoOwnerPayRates);
		systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		
		j.setMsg(message);
		return j;
	}


	/**
	 * 添加货主费率设置
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "save")
	@ResponseBody
	public AjaxJson save(CargoOwnerPayRatesEntity cargoOwnerPayRates, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		if (StringUtil.isNotEmpty(cargoOwnerPayRates.getId())) {
			message = "货主费率设置更新成功";
			CargoOwnerPayRatesEntity t = cargoOwnerPayRatesService.get(CargoOwnerPayRatesEntity.class, cargoOwnerPayRates.getId());
			try {
				MyBeanUtils.copyBeanNotNull2Bean(cargoOwnerPayRates, t);
				cargoOwnerPayRatesService.saveOrUpdate(t);
				systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
			} catch (Exception e) {
				e.printStackTrace();
				message = "货主费率设置更新失败";
			}
		} else {
			message = "货主费率设置添加成功";
			cargoOwnerPayRatesService.save(cargoOwnerPayRates);
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 货主费率设置列表页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "addorupdate")
	public ModelAndView addorupdate(CargoOwnerPayRatesEntity cargoOwnerPayRates, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(cargoOwnerPayRates.getId())) {
			cargoOwnerPayRates = cargoOwnerPayRatesService.getEntity(CargoOwnerPayRatesEntity.class, cargoOwnerPayRates.getId());
			req.setAttribute("cargoOwnerPayRatesPage", cargoOwnerPayRates);
		}
		return new ModelAndView("net/lahuobao/finance/payrate/cargoOwnerPayRates");
	}
	
	@RequestMapping(method = RequestMethod.GET)
	@ResponseBody
	public List<CargoOwnerPayRatesEntity> list() {
		List<CargoOwnerPayRatesEntity> listCargoOwnerPayRatess=cargoOwnerPayRatesService.getList(CargoOwnerPayRatesEntity.class);
		return listCargoOwnerPayRatess;
	}
	
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	@ResponseBody
	public ResponseEntity<?> get(@PathVariable("id") String id) {
		CargoOwnerPayRatesEntity task = cargoOwnerPayRatesService.get(CargoOwnerPayRatesEntity.class, id);
		if (task == null) {
			return new ResponseEntity(HttpStatus.NOT_FOUND);
		}
		return new ResponseEntity(task, HttpStatus.OK);
	}

	@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public ResponseEntity<?> create(@RequestBody CargoOwnerPayRatesEntity cargoOwnerPayRates, UriComponentsBuilder uriBuilder) {
		//调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
		Set<ConstraintViolation<CargoOwnerPayRatesEntity>> failures = validator.validate(cargoOwnerPayRates);
		if (!failures.isEmpty()) {
			return new ResponseEntity(BeanValidators.extractPropertyAndMessage(failures), HttpStatus.BAD_REQUEST);
		}

		//保存
		cargoOwnerPayRatesService.save(cargoOwnerPayRates);

		//按照Restful风格约定，创建指向新任务的url, 也可以直接返回id或对象.
		String id = cargoOwnerPayRates.getId();
		URI uri = uriBuilder.path("/rest/cargoOwnerPayRatesController/" + id).build().toUri();
		HttpHeaders headers = new HttpHeaders();
		headers.setLocation(uri);

		return new ResponseEntity(headers, HttpStatus.CREATED);
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<?> update(@RequestBody CargoOwnerPayRatesEntity cargoOwnerPayRates) {
		//调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
		Set<ConstraintViolation<CargoOwnerPayRatesEntity>> failures = validator.validate(cargoOwnerPayRates);
		if (!failures.isEmpty()) {
			return new ResponseEntity(BeanValidators.extractPropertyAndMessage(failures), HttpStatus.BAD_REQUEST);
		}

		//保存
		cargoOwnerPayRatesService.saveOrUpdate(cargoOwnerPayRates);

		//按Restful约定，返回204状态码, 无内容. 也可以返回200状态码.
		return new ResponseEntity(HttpStatus.NO_CONTENT);
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	@ResponseStatus(HttpStatus.NO_CONTENT)
	public void delete(@PathVariable("id") String id) {
		cargoOwnerPayRatesService.deleteEntityById(CargoOwnerPayRatesEntity.class, id);
	}



	@RequestMapping(params = "quotaAudit")
	@ResponseBody
	public Map<String,Object> quotaAudit(Integer aid,String auditMsg,Integer type) throws Exception {
		TSUser user = ResourceUtil.getSessionUserName();
		Map<String,Object> result = null;
		if(type.intValue() == 1){				//通过
			result = accreditService.quotaAudit(aid,user.getId(),user.getUserName(),auditMsg);
		}else{									//驳回
			result = accreditService.reject(aid, user.getId(), user.getUserName(), auditMsg);
		}
		return result;
	}






}
